//    用于压缩图片的canvas

var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
//    瓦片canvas
var tCanvas = document.createElement("canvas");
var tctx = tCanvas.getContext("2d");
var maxsize = 100 * 1000;
var i = 0;
/**
* 压缩预处理
* @param oFile //文件源
* @param formData //表单元素
* @param filename //文件名
* @param num //超过rule_size的文件数量
* @param rule_size //规定上传文件大小
* @param img_size //文件大小
* @param url //后台处理地址
*
* */
function compress_pre(oFile, formData, filename, num, rule_size, img_size, url) {
    if( img_size > rule_size ){
        var reader = new FileReader();
        reader.onload = function () {
            var result = this.result;
            var img = new Image();
            img.src = result;
//                图片加载完毕之后进行压缩，然后上传
            if (img.complete) {
                callback();
            } else {
                img.onload = callback
            }
            function callback() {
                i++;
                var data = compress(img);
                var blob = dataURLtoBlob(data);
                formData.append("goods_pic["+filename+"]",blob,oFile['name']);
                if(i===num){
                    upload(formData, url);
                    i=0;//清空计数
                }
                img = null;
            }
        };
        reader.readAsDataURL(oFile);
    }
    else{
        formData.append("goods_pic["+filename+"]",oFile);
        if(i===num){
            upload(formData, url);
            i=0;//清空计数
        }
    }
}

//压缩
function compress(img) {
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;

    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
    var ratio = (width * height) / (2000 * 2000);
    if (ratio > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
    } else {
        ratio = 1;
    }
    // 设置canvas的宽高
    canvas.width = width;
    canvas.height = height;

//        铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    //如果图片像素大于100万则使用瓦片绘制
    var count = width * height / maxsize;
    if (count > 1) {
        count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片

//            计算每块瓦片的宽和高
        var nw = ~~(width / count);
        var nh = ~~(height / count);

        tCanvas.width = nw;
        tCanvas.height = nh;

        for (var i = 0; i < count; i++) {
            for (var j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);

                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
            }
        }
    } else {
        ctx.drawImage(img, 0, 0, width, height);
    }
    var ndata = '';
    //进行最小压缩
    if(initSize>4*1024*1024){
        ndata = canvas.toDataURL('image/jpeg', 0.3);
    }else{
        ndata = canvas.toDataURL('image/jpeg', 0.6);
    }

    console.log('压缩前：' + initSize);
    console.log('压缩后：' + ndata.length);
    console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
    return ndata;
}

//返回blob
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type: mime});
}

//xhr上传
function upload(formData, url) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', url, true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState==4 && xhr.status==200){
            $('.fadeCont .upload').hide();
            var res = JSON.parse(xhr.responseText);
            if(res['status']==1){
                all_img.clear();
                $('.fadeCont .right').show();
                $('.fadeCont .tip').show();
            }else{
                $('.fadeBox.tip h4').text('提交失败');
                $('.fadeBox.tip p').text(res['msg']);
                $('.fadeBox.tip a').css("background-color",'#ff4e00');
                $('.fadeCont .wrong').show();
                $('.fadeCont .tip').show();
            }
        }
    };
    xhr.send(formData);
}
